package org.light.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.List;

import org.light.core.Writeable;
import org.light.domain.DragonHideStatement;
import org.light.domain.Statement;
import org.light.domain.StatementList;

public class WriteableUtil {
	public static StatementList merge(List<Writeable> cw){
		StatementList sc = new StatementList();
		Collections.sort(cw);
		long ii = 100;
		for (Writeable wc:cw){
			if (wc instanceof StatementList){
				List<Statement> list = ((StatementList) wc).getStatementList();
				Collections.sort(list);
				for (Statement s:list){
					if (s instanceof DragonHideStatement){
						DragonHideStatement ds = (DragonHideStatement)s;
						if (ds.isDragonShow()){
							Statement ss = ds.getNormalStatement();
							ss.setSerial(ii);
							sc.add(ss);
							ii += 100;
						}
					} else if (s instanceof Statement) {
						Statement ss = (Statement)s;
						ss.setSerial(ii);
						sc.add(ss);
						ii += 100;
					}
				}
			} else if (wc instanceof DragonHideStatement) {
				DragonHideStatement ds = (DragonHideStatement)wc;
				if (ds.isDragonShow()){
					Statement dss = ds.getNormalStatement();
					dss.setSerial(ii);
					sc.add(dss);
					ii += 100;
				}
			} else if (wc instanceof Statement) {
				Statement s = (Statement)wc;
				s.setSerial(ii);
				sc.add(s);
				ii += 100;
			}
		}
		return sc;
	}
	
	public static void writeToFile(String filePath, String content) throws Exception {
		File f = new File(filePath);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.createNewFile();
		try (Writer fw = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(f.getAbsolutePath()), "UTF-8"))) {
			fw.write(content, 0, content.length());
		}
	}
}
